package com.xjm.service.serviceImpl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xjm.config.AppConfig;
import com.xjm.constant.AppConst;
import com.xjm.service.WxService;
import com.xjm.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class WxServiceImpl implements WxService {

    private static final String PREFIX = "https://api.weixin.qq.com";
    private final AppConfig appConfig;
    private final RedisUtil redisUtil;

    @Override
    public String getOpenId(String code) {
        String openId = null;
        Map<String, Object> query = new HashMap<>();
        query.put("appid", appConfig.getAppid());
        query.put("secret", appConfig.getSecret());
        query.put("js_code", code);
        String result = HttpUtil.get(PREFIX + "/sns/jscode2session", query);
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if (jsonResult.getByPath("openid") != null) {
            openId = jsonResult.getStr("openid");
        }
        return openId;
    }


    /**
     * 获取access_token
     *
     * @return access_token
     */
    private String getAccessToken() {
        if (redisUtil.getExpire(AppConst.MIN_TOKEN) > 0) {
            return redisUtil.getStr(AppConst.MIN_TOKEN);
        }
        Map<String, Object> query = new HashMap<>();
        query.put("appid", appConfig.getAppid());
        query.put("secret", appConfig.getSecret());
        query.put("grant_type", "client_credential");
        String result = HttpUtil.get(PREFIX + "/cgi-bin/token", query);
        JSONObject jsonResult = JSONUtil.parseObj(result);
        if (jsonResult.getByPath("access_token") != null) {
            redisUtil.set(AppConst.MIN_TOKEN, jsonResult.getByPath("access_token"), jsonResult.getLong("expires_in") - 200);
            return jsonResult.getStr("access_token");
        }
        return null;
    }
}
